package com.xls.recycleranimation;

import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{


    private SwipeRefreshLayout srlLayout;
    private RecyclerView recyclerView;
    private MessageAdapter mAdapter;
    private Button addBtn;
    private Button deleteBtn;
    List<MessageInfo> mList = new ArrayList<>();
    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 1:
                    if(srlLayout!=null && srlLayout.isRefreshing()){
                        srlLayout.setRefreshing(false);
                        mAdapter.setList(getTestData());
                    }
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        srlLayout = (SwipeRefreshLayout) findViewById(R.id.srlLayout);
        recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        srlLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mHandler.sendEmptyMessageDelayed(1,1000);
            }
        });

        mAdapter = new MessageAdapter();
        recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this,LinearLayoutManager.VERTICAL,false));
        recyclerView.addItemDecoration(new SpaceItemDecoration(1, 10, false));
        recyclerView.setItemAnimator(new MyItemAnimator());
        recyclerView.setAdapter(mAdapter);

        addBtn = (Button) findViewById(R.id.btn_add);
        deleteBtn = (Button) findViewById(R.id.btn_delete);
        addBtn.setOnClickListener(this);
        deleteBtn.setOnClickListener(this);

    }




    private List<MessageInfo> getTestData(){

        for(int i=0;i<20;i++){
            MessageInfo info = new MessageInfo("xiongliangshan"+i,System.currentTimeMillis());
            mList.add(info);
        }

        return mList;
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_add:
                mAdapter.addItem(new MessageInfo("add",System.currentTimeMillis()));
                recyclerView.scrollToPosition(0);
                break;
            case R.id.btn_delete:
                mAdapter.removeItem();
                break;
        }
    }
}
